<script lang="ts">
import { defineComponent } from "vue";
import { ElForm, ElFormItem, ElInput, ElButton } from "element-plus";
import md5 from "md5";

export default defineComponent({
  name: "Login",
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
  },
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, message: "Please enter username", trigger: "blur" },
        ],
        password: [
          { required: true, message: "Please enter password", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async login() {
      try {
        console.log(JSON.stringify(this.loginForm));
        
        // 对密码进行 MD5 加密
        const encryptedPassword = md5(this.loginForm.password);

        // 构造请求体
        const requestBody = {
          username: this.loginForm.username,
          password: encryptedPassword,
        };

        // 发送登录请求
        const response = await fetch("http://localhost:8080/api/user/login", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(requestBody),
        }).then((res) => res.json());

        // 如果登录成功，跳转到首页
        if (response.success) {
          alert("Login success");
          // 将 token 存储在本地存储中
          localStorage.setItem("token", response.token);
          // 跳转到首页
          this.$router.push("/index");
        } else {
          // 处理登录失败
          alert("Login failed");
          // 给用户一个提示
        }
      } catch (e) {
        alert("Login failed");
        // 给用户一个提示
      }
    },
  },
});
</script>

<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="Username"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="Password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">Login</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-form {
  width: 300px;
}
</style>
